// @login 和 register
const express = require("express");
const router = express.Router();
const jwt = require('jsonwebtoken');
const keys = "secret";
const passport = require("passport");
const User = require("../models/user");

// $route get 请求 api/users/test
// @desc 返回请求的json数据
// @access public 
router.get("/test", (req, res) => {
    res.json({ msg: "test success!!!" })
})

// $route get 请求 api/users/register
// @desc 返回请求的json数据
// @access public 
router.post("/register", (req, res) => {
    //查询数据库是否有数据
    User.findOne({ username: req.body.username }).then((user) => {
        if (user) {
            return res.status(400).json("用户被注册")
        } else {
            const newUser = new User({
                username: req.body.username,
                password: req.body.password,
            });
            newUser.save().then(user => res.json(user)).catch(err => console.log(err))
        }
    })
})

// $route post 请求 api/users/login
// @desc 返回token jwt passport
// @access public 
router.post("/login", (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    User.findOne({ username }).then(user => {
        if (!user) {
            return res.status(404).json("用户不存在");
        } else {
            // 密码匹配
            if (password == user.password) {
                const rule = {
                    id: user.id,
                    username: user.username,
                };
                jwt.sign(rule, keys, { expiresIn: 3600 }, (err, token) => {
                    if (err) throw err;
                    res.json({
                        success: true,
                        token: "Bearer " + token
                    });
                })
            } else {
                return res.status(400).json("密码错误！");
            }
        }
    })
})

// $route get 请求 api/users/info 用户信息
// @desc 返回 info user
// @access private
router.get("/info", passport.authenticate("jwt", { session: false }), (req, res) => {
    res.json({
        id: req.user.id,
        username: req.user.username,
        date:req.user.date
    });
})

// $route post 请求 api/users/updataPassword 更改密码
// @desc 返回 新密码
// @access private
router.post("/updataPassword", (req, res) => {
    let newPassword = req.body.password;
    User.update({ _id: req.body.id }, { $set: { password: newPassword } }, (error) => {
        if (error) {
            res.json({ message: '密码修改失败' })
        }
        else {
            res.json({ message: '密码修改成功' })
        }
    })

})

module.exports = router;